package org.itboys.weixin.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.weixin.constant.WeixinConstants;
import org.itboys.weixin.dto.WeixinResult;
import org.itboys.weixin.entity.WeixinMenu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信菜单相关工具类
 * @author ChenJunhui
 *
 */
public class WeixinMenuUtils {

	private static  Logger logger = LoggerFactory.getLogger(WeixinMenuUtils.class);
	
	/**
	 * 创建微信自定义菜单
	 * @author Chenjunhui
	 * @param appId
	 * @param appScret
	 * @param menus 微信菜单
	 * @return 1:成功 -1:https请求失败 -2:返回结果创建失败 0:异常
	 */
	public static int doCreateWeixinMenu(String appId, String appSecret,List<WeixinMenu> menus) {
		String jsonMenu = menu2Json(menus);
		System.out.println(jsonMenu);
		return doCreateWeixinMenu(appId, appSecret, jsonMenu);
	}

	/**
	 * 创建微信自定义菜单
	 * @author Chenjunhui
	 * @param appId
	 * @param appScret
	 * @param jsonMenu 自定义菜单json字符串
	 * @return 1:成功 -1:https请求失败 -2:返回结果创建失败 0:异常
	 */
	public static int doCreateWeixinMenu(String appId, String appSecret,String jsonMenu) {
		String accessToken = WeixinUtils.getAccessToken(appId, appSecret);
		String createMenuUrl = WeixinConstants.URL.CREATE_MENU_URL+accessToken;
		PostMethod postMethod = new PostMethod(createMenuUrl);
		RequestEntity  requestEntity = null;
		try {
			requestEntity = new StringRequestEntity(jsonMenu,CommonConstants.CONTENT_TYPE.JSON_TYPE ,CommonConstants.ENCODE.UTF_8); 
			postMethod.setRequestEntity(requestEntity);  
			HttpClient httpclient = HttpHelper.getHttpClient();
			 int statusCode = httpclient.executeMethod(postMethod);
			 if (statusCode != HttpStatus.SC_OK) {
		    	 logger.error("doCreateWeixinMenu error statusCode={} appId={} appScret={} jsonaMenu={}",new Object[]{statusCode,appId,appSecret,jsonMenu});
		    	 return -1;
		    }
			String createResult = postMethod.getResponseBodyAsString();
			WeixinResult result = JsonUtils.jsonToObject(WeixinResult.class, createResult);
			if(result.getErrcode()!=0){
				logger.error("doCreateWeixinMenu return error errorCode={} errmsg={} appId={} appScret={} jsonMenu={}",new Object[]{result.getErrcode(),result.getErrmsg(),appId,appSecret,jsonMenu});
				return -2;
				
			}
			return 1;//成功
		} catch (Exception e) {
			logger.error("doCreateWeixinMenu Exception appId="+appId+",appScret="+appSecret+",jsonMenu="+jsonMenu,e);
			return 0;
		}finally{
			if(postMethod!=null){
				postMethod.releaseConnection();
			}
		}
	}
	
	/**
	 * 微信菜单转json
	 * @author Administrator
	 * @param menus
	 * @return
	 */
	public static String menu2Json(List<WeixinMenu> menus) {
		// 反正这个很少会执行 先浪费些空间 用map
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		for (WeixinMenu menu : menus) {
			if (menu.getParentId() == 0) {
				Map<String, Object> menuMap = new HashMap<String, Object>();
				menuMap.put("name", menu.getName());
				if (menu.getParentId() == 0) {
					if(!WeixinMenu.TYPE_PARENT.equals(menu.getType())){
						menuMap.put("type", menu.getType());
						if (WeixinMenu.TYPE_VIEW.equals(menu.getType())) {
							menuMap.put("url", menu.getValue());
						} else {
							menuMap.put("key", menu.getValue());
						}
					}else{
						List<Map<String, Object>> subButtons = new ArrayList<Map<String, Object>>();
						for (WeixinMenu child : menus) {
							if (child.getParentId().equals(menu.getId())) {
								Map<String, Object> childMap = new HashMap<String, Object>();
								childMap.put("name", child.getName());
								childMap.put("type", child.getType());
								if (WeixinMenu.TYPE_VIEW.equals(child.getType())) {
									childMap.put("url", child.getValue());
								} else {
									childMap.put("key", child.getValue());
								}
								subButtons.add(childMap);
							}
						}
						menuMap.put("sub_button", subButtons);
					}
				} 
				list.add(menuMap);
			}
		}
		Map<String, Object> resultMap = new HashMap<String, Object>(2);
		resultMap.put("button", list);
		return JsonUtils.objectToString(resultMap);
	}
}
